﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Admin_Suatintuc : System.Web.UI.Page
{
    BUS_News objP = new BUS_News();
    BUS_Category objC = new BUS_Category();
    protected void Page_Load(object sender, EventArgs e)
    {
        string strcid = "", strpid = "";
        Page.Title = "Sửa Tin Tức";
        if (!IsPostBack)
        {
            if (Session["AdminLogin"] != null)
            {
                strcid = Request.QueryString.Get("cid");
                strpid = Request.QueryString.Get("id");
                if (strcid == null || strpid == null)
                {
                    Response.Redirect("Tintuc.aspx");
                }
                else
                {
                    LoadData(Convert.ToInt16(Request.QueryString.Get("cid")), Convert.ToInt16(Request.QueryString.Get("id")));
                }
            }
            else Response.Redirect("Dangnhap.aspx");
        }
    }
    public void LoadData(int cgid, int pid)
    {
        try
        {
            int  Category_Id, status;
            var dataC = objC.Category_getById(cgid);
            var dataP = objP.News_getAllByPid(pid);
            //var dataM = objM.Maker_getAllById(pid);
            //Maker_Id = int.Parse(dataP.Rows[0]["Maker_Id"].ToString());
            Category_Id = int.Parse(dataP.Rows[0]["Type"].ToString());
            status = int.Parse(dataP.Rows[0]["Status"].ToString());
            //var tamM = objM.Maker_getAllById(Maker_Id);
            linkxemtt.NavigateUrl = "Xemtintuc.aspx?cid=" + cgid + "&id=" + pid;
            linksuatt.NavigateUrl = "Suatintuc.aspx?cid=" + cgid + "&id=" + pid;
            linkthemtt.NavigateUrl = "Themtintuc.aspx";
            lienKet.Text = dataC.Rows[0]["Name"].ToString();
            //tentintuc.Text = dataP.Rows[0]["title"].ToString();
            tentt.Text = dataP.Rows[0]["Title"].ToString();
            EditorSumary.Text = dataP.Rows[0]["Contents"].ToString();
            //giasanpham.Text = dataP.Rows[0]["Price"].ToString();
            //giakhuyenmai.Text = dataP.Rows[0]["PriceNew"].ToString();
            //vitri.Text = dataP.Rows[0]["Order"].ToString();
            //hinhsanphamnho.ImageUrl = "~/Uploads/Product/Small/" + dataP.Rows[0]["ImageSmall"].ToString();
            hinhanhtintuc.ImageUrl = "~/Uploads/News/" + dataP.Rows[0]["Image"].ToString();
            ////load du lieu len dropdownlist loai san pham
            droploaitt.DataSource = objC.Category_getData();//Category_getById(Category_Id);
            droploaitt.DataTextField = "Name";
            droploaitt.DataValueField = "Cgid";
            droploaitt.SelectedIndex = Category_Id - 1;
            droploaitt.DataBind();
            ////load du lieu len dropdownlist nha san xuat
            //dropnxs.DataSource = objM.Maker_getData();
            //dropnxs.DataTextField = "Name";
            //dropnxs.DataValueField = "ID";
            //dropnxs.SelectedIndex = Maker_Id - 1;
            //dropnxs.DataBind();

            if (status == 1)
            {
                droptrangthai.SelectedIndex = 0;
            }
            else droptrangthai.SelectedIndex = 1;
        }
        catch
        {
        }

    }
    protected void btncapnhatsp_Click(object sender, EventArgs e)
    {
        try
        {
            DTO_News dtoP = new DTO_News();
            int cid = Convert.ToInt16(Request.QueryString.Get("cid"));
            int pid = Convert.ToInt16(Request.QueryString.Get("id"));
            dtoP.ID = pid;
            if (tentt.Text != "" && EditorSumary.Text != "")
            {
                dtoP.Title = tentt.Text.Trim();
                dtoP.Type = int.Parse(droploaitt.SelectedValue.ToString()); ;
                dtoP.Contents = EditorSumary.Text.Trim();
                //dtoP.Price = float.Parse(giasanpham.Text.Trim());
                if (uploadanhtintuc.FileName != string.Empty)
                {
                    Session["isChangePic"] = true;
                    dtoP.Image = uploadanhtintuc.FileName.Substring(uploadanhtintuc.FileName.LastIndexOf(@"\") + 1);
                    if (!UploadImage(dtoP.Image))
                        return;
                }
                else
                {
                    Session["isChangePic"] = false;
                }

                //if (uploadanhnho.FileName != string.Empty)
                //{
                //    Session["isChangePic1"] = true;
                //    dtoP.ImageSmall = uploadanhnho.FileName.Substring(uploadanhnho.FileName.LastIndexOf(@"\") + 1);
                //    if (!UploadImageSmall(dtoP.ImageSmall))
                //        return;
                //}
                //else
                //{
                //    Session["isChangePic1"] = false;
                //}
                //if (chkgiakhuyenmai.Checked)
                //{
                //    dtoP.PriceNew = float.Parse(giakhuyenmai.Text.Trim());
                //}
                //else dtoP.PriceNew = 0;

                //dtoP.Order = int.Parse(vitri.Text.Trim());
                //dtoP.Status = int.Parse(droptrangthai.SelectedValue.ToString());
                //dtoP.Maker_Id = int.Parse(dropnxs.SelectedValue.ToString());
                //dtoP.Category_Id = int.Parse(droploaisp.SelectedValue.ToString());

                if (!(bool)Session["isChangePic"])
                {
                    dtoP.Image = hinhanhtintuc.ImageUrl.Substring(hinhanhtintuc.ImageUrl.LastIndexOf("/") + 1);
                }
                //if (!(bool)Session["isChangePic1"])
                //{
                //    dtoP.Image = hinhanhtintuc.ImageUrl.Substring(hinhanhtintuc.ImageUrl.LastIndexOf("/") + 1);
                //}
                if (objP.News_Update(dtoP))
                {
                    Response.Write("<script>alert(\"Cập nhật thông tin thành công <..*!>\")</script>");
                    Response.Redirect("Xemtintuc.aspx?cid=" + cid + "&id=" + pid);
                }
                else Response.Write("<script>alert(\"Cập nhật không thành công <..*!>\")</script>");
            }
            else
            {
                Response.Write("<script>alert(\"Vui lòng điền đầy đủ thông tin có (*)\")</script>");
            }

        }
        catch (Exception ex)
        {

            Response.Write("<script>alert(\"Lỗi " + ex.Message + " <..*!>\")</script>");
        }

    }

    //Phuong thuc upload anh
    public bool UploadImage(string imagelargename)
    {
        bool complete = false;
        //Lay ve ten file anh
        string fname = uploadanhtintuc.FileName;
        //Tach ten file
        string[] tokens = fname.Split(new char[] { '.' });
        //Luu tru dung luong file tinh bang byte
        int bytes = uploadanhtintuc.FileBytes.Length;
        //Kiem tra dung luong file anh
        if (bytes > (1024 * 1024))
        {
            lblargeerr.Text = "Dung lượng ảnh phải nhỏ hơn 4KB";
            return false;
        }
        //Kiem tra dang file upload
        if (tokens[tokens.Length - 1] == "jpg" || tokens[tokens.Length - 1] == "jpeg" || tokens[tokens.Length - 1] == "png" || tokens[tokens.Length - 1] == "gif")
        {
            //Khai bao bien luu tru duong dan den thu muc images
            string relPath = Server.MapPath("..\\.");
            //Khai bao bien luu tru duong dan tuyet doi
            string absolutePath = relPath + "\\Uploads\\News\\" + imagelargename;
            //Luu len server
            uploadanhtintuc.SaveAs(absolutePath);
            complete = true;
        }
        else
        {
            lblargeerr.Text = "Đây không phải file ảnh.";
            return false;
        }
        return complete;
    }
}